<template>
  <div class="settings">
    <h1>系统设置</h1>
    
    <el-card class="settings-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本设置" name="basic">
          <el-form :model="settingsForm" :rules="rules" ref="settingsFormRef" label-width="120px">
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="settingsForm.systemName"></el-input>
            </el-form-item>
            <el-form-item label="系统版本" prop="version">
              <el-input v-model="settingsForm.version" disabled></el-input>
            </el-form-item>
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="settingsForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
            </el-form-item>
            <el-form-item label="网站地址" prop="website">
              <el-input v-model="settingsForm.website" placeholder="请输入网站地址"></el-input>
            </el-form-item>
            <el-form-item label="自动登录" prop="autoLogin">
              <el-switch v-model="settingsForm.autoLogin"></el-switch>
            </el-form-item>
            <el-form-item label="主题颜色" prop="themeColor">
              <el-color-picker v-model="settingsForm.themeColor"></el-color-picker>
            </el-form-item>
            <el-form-item label="默认语言" prop="defaultLanguage">
              <el-radio-group v-model="settingsForm.defaultLanguage">
                <el-radio label="zh-CN">简体中文</el-radio>
                <el-radio label="en-US">English</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveSettings">保存设置</el-button>
              <el-button @click="handleResetSettings">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="安全设置" name="security">
          <el-form :model="securityForm" :rules="securityRules" ref="securityFormRef" label-width="120px">
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input v-model="securityForm.oldPassword" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="securityForm.newPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="securityForm.confirmPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="用户信息" name="profile">
          <div class="profile-info">
            <div class="profile-header">
              <el-avatar size="120" :src="currentUser.avatar || ''">
                {{ getAvatarText(currentUser.name || currentUser.username) }}
              </el-avatar>
              <div class="profile-details">
                <h3>{{ currentUser.name || currentUser.username }}</h3>
                <p>{{ getRoleLabel(currentUser.role) }}</p>
                <p>账号状态: 
                  <el-tag :type="currentUser.status === 'active' ? 'success' : 'danger'">
                    {{ currentUser.status === 'active' ? '活跃' : '禁用' }}
                  </el-tag>
                </p>
                <p>注册时间: {{ formatDate(currentUser.createTime) }}</p>
              </div>
            </div>
            
            <el-divider></el-divider>
            
            <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="120px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="profileForm.username" disabled></el-input>
              </el-form-item>
              <el-form-item label="真实姓名" prop="name">
                <el-input v-model="profileForm.name" placeholder="请输入真实姓名"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileForm.email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleUpdateProfile">更新信息</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="系统日志" name="logs">
          <div class="logs-section">
            <el-input
              v-model="logSearch"
              placeholder="搜索日志内容"
              prefix-icon="el-icon-search"
              clearable
              class="log-search"
            ></el-input>
            
            <el-table :data="filteredLogs" style="width: 100%">
              <el-table-column prop="time" label="时间" width="180"></el-table-column>
              <el-table-column prop="user" label="操作人" width="120"></el-table-column>
              <el-table-column prop="action" label="操作" width="150"></el-table-column>
              <el-table-column prop="content" label="内容"></el-table-column>
              <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
            </el-table>
            
            <div class="pagination">
              <el-pagination
                v-model:current-page="logPagination.currentPage"
                v-model:page-size="logPagination.pageSize"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="filteredLogs.length"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { api } from '../utils/axios'
const { get, post, put, delete: del } = api
import { ElMessage } from 'element-plus'
import { systemSettings, users } from '../utils/mockData.js'

// 当前激活的标签页
const activeTab = ref('basic')

// 设置表单
const settingsFormRef = ref()
const settingsForm = reactive({
  systemName: '',
  version: '',
  contactEmail: '',
  website: '',
  autoLogin: false,
  themeColor: '#409eff',
  defaultLanguage: 'zh-CN'
})

// 安全设置表单
const securityFormRef = ref()
const securityForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 个人信息表单
const profileFormRef = ref()
const profileForm = reactive({
  username: '',
  name: '',
  email: ''
})

// 当前用户信息
const currentUser = ref({})

// 日志搜索和分页
const logSearch = ref('')
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 模拟日志数据
const logs = ref([
  { id: 1, time: '2023-06-01 10:23:45', user: 'admin', action: '登录', content: '用户登录系统', ip: '192.168.1.100' },
  { id: 2, time: '2023-06-01 11:05:23', user: 'admin', action: '更新', content: '修改系统设置', ip: '192.168.1.100' },
  { id: 3, time: '2023-06-01 13:45:12', user: 'user1', action: '查看', content: '查看产品列表', ip: '192.168.1.101' },
  { id: 4, time: '2023-06-01 14:20:33', user: 'admin', action: '创建', content: '创建新用户', ip: '192.168.1.100' },
  { id: 5, time: '2023-06-01 15:30:17', user: 'editor', action: '更新', content: '编辑产品信息', ip: '192.168.1.102' },
])

// 过滤后的日志
const filteredLogs = computed(() => {
  let result = [...logs.value]
  if (logSearch.value) {
    const keyword = logSearch.value.toLowerCase()
    result = result.filter(log => 
      log.content.toLowerCase().includes(keyword) ||
      log.user.toLowerCase().includes(keyword) ||
      log.action.toLowerCase().includes(keyword)
    )
  }
  return result
})

// 表单验证规则
const rules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '系统名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  website: [
    { type: 'url', message: '请输入正确的网站地址', trigger: 'blur' }
  ]
}

const securityRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== securityForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const profileRules = {
  name: [
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 获取角色标签
const getRoleLabel = (role) => {
  const roleMap = {
    admin: '管理员',
    editor: '编辑',
    user: '普通用户'
  }
  return roleMap[role] || role
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取头像文字
const getAvatarText = (name) => {
  if (!name) return '用'
  return name.charAt(0)
}

// 加载系统设置
const loadSettings = () => {
  Object.assign(settingsForm, systemSettings)
}

// 加载用户信息
const loadUserInfo = () => {
  // 从localStorage获取当前用户
  const userStr = localStorage.getItem('currentUser')
  if (userStr) {
    currentUser.value = JSON.parse(userStr)
    Object.assign(profileForm, {
      username: currentUser.value.username,
      name: currentUser.value.name || '',
      email: currentUser.value.email
    })
  } else {
    // 如果没有，使用默认管理员用户
    const adminUser = users.find(u => u.username === 'admin')
    if (adminUser) {
      currentUser.value = adminUser
      Object.assign(profileForm, {
        username: adminUser.username,
        name: adminUser.name || '',
        email: adminUser.email
      })
    }
  }
}

// 保存系统设置
const handleSaveSettings = async () => {
  await settingsFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      // 模拟保存设置
      setTimeout(() => {
        ElMessage.success('系统设置保存成功')
        // 可以在这里更新模拟数据
      }, 500)
    } catch (error) {
      ElMessage.error('保存失败，请重试')
    }
  })
}

// 重置系统设置
const handleResetSettings = () => {
  loadSettings()
  ElMessage.info('设置已重置')
}

// 修改密码
const handleChangePassword = async () => {
  await securityFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      // 模拟验证旧密码
      if (securityForm.oldPassword !== '123456') {
        ElMessage.error('旧密码错误')
        return
      }
      
      // 模拟保存新密码
      setTimeout(() => {
        ElMessage.success('密码修改成功')
        // 重置表单
        securityForm.oldPassword = ''
        securityForm.newPassword = ''
        securityForm.confirmPassword = ''
      }, 500)
    } catch (error) {
      ElMessage.error('修改失败，请重试')
    }
  })
}

// 更新个人信息
const handleUpdateProfile = async () => {
  await profileFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      // 模拟保存个人信息
      setTimeout(() => {
        Object.assign(currentUser.value, {
          name: profileForm.name,
          email: profileForm.email
        })
        // 更新localStorage中的用户信息
        localStorage.setItem('currentUser', JSON.stringify(currentUser.value))
        ElMessage.success('个人信息更新成功')
      }, 500)
    } catch (error) {
      ElMessage.error('更新失败，请重试')
    }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadSettings()
  loadUserInfo()
})
</script>

<style scoped>
.settings {
  padding: 20px;
  height: 100%;
}

.settings-card {
  height: calc(100% - 50px);
  display: flex;
  flex-direction: column;
}

.el-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.el-tabs__content {
  flex: 1;
  overflow: auto;
  padding: 20px 0;
}

.profile-info {
  max-width: 800px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.profile-details {
  margin-left: 40px;
}

.profile-details h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 20px;
}

.profile-details p {
  margin: 8px 0;
  color: #606266;
}

.logs-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.log-search {
  margin-bottom: 20px;
  width: 300px;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>